import 'package:flutter/material.dart';
import '../models/course.dart';
import '../services/course_service.dart';
import '../utils/theme_colors.dart';
import '../widgets/course_card.dart';
import '../widgets/course_filter_sheet.dart';
import 'course_detail_screen.dart';

class EducationTrainingScreen extends StatefulWidget {
  const EducationTrainingScreen({Key? key}) : super(key: key);

  @override
  State<EducationTrainingScreen> createState() => _EducationTrainingScreenState();
}

class _EducationTrainingScreenState extends State<EducationTrainingScreen>
    with TickerProviderStateMixin {
  late TabController _tabController;
  final CourseService _courseService = CourseService.instance;
  
  List<Course> _allCourses = [];
  List<Course> _filteredCourses = [];
  List<Course> _featuredCourses = [];
  List<Course> _popularCourses = [];
  List<Instructor> _instructors = [];
  
  CourseFilter _currentFilter = CourseFilter.all;
  bool _isLoading = true;
  String _searchQuery = '';
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);
    _loadData();
  }

  @override
  void dispose() {
    _tabController.dispose();
    _searchController.dispose();
    super.dispose();
  }

  Future<void> _loadData() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final courses = await _courseService.getCourses();
      final featured = await _courseService.getFeaturedCourses();
      final popular = await _courseService.getPopularCourses();
      final instructors = await _courseService.getInstructors();

      setState(() {
        _allCourses = courses;
        _filteredCourses = courses;
        _featuredCourses = featured;
        _popularCourses = popular;
        _instructors = instructors;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载失败: $e')),
      );
    }
  }

  void _applyFilter(CourseFilter filter) {
    setState(() {
      _currentFilter = filter;
      _filteredCourses = _courseService.filterCourses(_allCourses, filter);
    });
  }

  void _searchCourses(String query) {
    setState(() {
      _searchQuery = query;
      if (query.isEmpty) {
        _filteredCourses = _courseService.filterCourses(_allCourses, _currentFilter);
      } else {
        _filteredCourses = _allCourses
            .where((course) =>
                course.title.toLowerCase().contains(query.toLowerCase()) ||
                course.description.toLowerCase().contains(query.toLowerCase()))
            .toList();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.background,
      body: Column(
        children: [
          _buildHeader(),
          _buildTabBar(),
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildCourseListPage(),
                _buildLearningPathPage(),
                _buildInstructorPage(),
                _buildCommunityPage(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
      color: Colors.white,
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: Container(
                  height: 40,
                  decoration: BoxDecoration(
                    color: ThemeColors.background,
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: TextField(
                    controller: _searchController,
                    onChanged: _searchCourses,
                    decoration: InputDecoration(
                      hintText: '搜索课程...',
                      prefixIcon: Icon(
                        Icons.search,
                        color: ThemeColors.textSecondary,
                        size: 20,
                      ),
                      border: InputBorder.none,
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 10,
                      ),
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 12),
              GestureDetector(
                onTap: _showFilterSheet,
                child: Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: ThemeColors.primary,
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: const Icon(
                    Icons.tune,
                    color: Colors.white,
                    size: 20,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildTabBar() {
    return Container(
      color: Colors.white,
      child: TabBar(
        controller: _tabController,
        labelColor: ThemeColors.primary,
        unselectedLabelColor: ThemeColors.textSecondary,
        indicatorColor: ThemeColors.primary,
        indicatorWeight: 3,
        labelStyle: const TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w600,
        ),
        unselectedLabelStyle: const TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.normal,
        ),
        tabs: const [
          Tab(text: '课程体系'),
          Tab(text: '学习路径'),
          Tab(text: '师资介绍'),
          Tab(text: '学习社区'),
        ],
      ),
    );
  }

  Widget _buildCourseListPage() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    return RefreshIndicator(
      onRefresh: _loadData,
      child: CustomScrollView(
        slivers: [
          // 精选课程
          if (_featuredCourses.isNotEmpty) ...[
            SliverToBoxAdapter(
              child: _buildSectionHeader('精选课程', '为您推荐的优质课程'),
            ),
            SliverToBoxAdapter(
              child: _buildFeaturedCourses(),
            ),
          ],
          
          // 热门课程
          if (_popularCourses.isNotEmpty) ...[
            SliverToBoxAdapter(
              child: _buildSectionHeader('热门课程', '最受欢迎的课程'),
            ),
            SliverToBoxAdapter(
              child: _buildPopularCourses(),
            ),
          ],
          
          // 课程分类
          SliverToBoxAdapter(
            child: _buildSectionHeader('课程分类', '按类型浏览课程'),
          ),
          SliverToBoxAdapter(
            child: _buildCourseCategories(),
          ),
          
          // 所有课程
          SliverToBoxAdapter(
            child: _buildSectionHeader(
              '所有课程',
              '共${_filteredCourses.length}门课程',
            ),
          ),
          SliverPadding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            sliver: SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  final course = _filteredCourses[index];
                  return Padding(
                    padding: const EdgeInsets.only(bottom: 12),
                    child: CourseCard(
                      course: course,
                      onTap: () => _navigateToCourseDetail(course),
                    ),
                  );
                },
                childCount: _filteredCourses.length,
              ),
            ),
          ),
          const SliverToBoxAdapter(
            child: SizedBox(height: 20),
          ),
        ],
      ),
    );
  }

  Widget _buildLearningPathPage() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildPathCard(
            '传统技艺入门',
            '从零开始学习传统手工艺',
            ['基础理论', '工具认识', '简单制作', '作品展示'],
            Colors.blue,
            Icons.palette,
          ),
          const SizedBox(height: 16),
          _buildPathCard(
            '文化传承进阶',
            '深入了解非遗文化内涵',
            ['历史背景', '文化意义', '传承方式', '创新发展'],
            Colors.green,
            Icons.school,
          ),
          const SizedBox(height: 16),
          _buildPathCard(
            '技艺大师之路',
            '成为传统技艺传承人',
            ['高级技法', '创作实践', '教学能力', '文化推广'],
            Colors.orange,
            Icons.star,
          ),
        ],
      ),
    );
  }

  Widget _buildInstructorPage() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _instructors.length,
      itemBuilder: (context, index) {
        final instructor = _instructors[index];
        return _buildInstructorCard(instructor);
      },
    );
  }

  Widget _buildCommunityPage() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildCommunitySection(
            '学习讨论',
            '与同学交流学习心得',
            Icons.forum,
            Colors.blue,
          ),
          const SizedBox(height: 16),
          _buildCommunitySection(
            '作品展示',
            '分享您的学习成果',
            Icons.photo_library,
            Colors.green,
          ),
          const SizedBox(height: 16),
          _buildCommunitySection(
            '问答互助',
            '解答学习中的疑问',
            Icons.help_outline,
            Colors.orange,
          ),
          const SizedBox(height: 16),
          _buildCommunitySection(
            '活动通知',
            '获取最新活动信息',
            Icons.notifications,
            Colors.purple,
          ),
        ],
      ),
    );
  }

  Widget _buildSectionHeader(String title, String subtitle) {
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 20, 16, 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                title,
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 4),
              Text(
                subtitle,
                style: TextStyle(
                  fontSize: 12,
                  color: ThemeColors.textSecondary,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildFeaturedCourses() {
    return SizedBox(
      height: 200,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        itemCount: _featuredCourses.length,
        itemBuilder: (context, index) {
          final course = _featuredCourses[index];
          return Container(
            width: 280,
            margin: const EdgeInsets.only(right: 12),
            child: CourseCard(
              course: course,
              onTap: () => _navigateToCourseDetail(course),
            ),
          );
        },
      ),
    );
  }

  Widget _buildPopularCourses() {
    return SizedBox(
      height: 120,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        itemCount: _popularCourses.length,
        itemBuilder: (context, index) {
          final course = _popularCourses[index];
          return Container(
            width: 200,
            margin: const EdgeInsets.only(right: 12),
            child: _buildCompactCourseCard(course),
          );
        },
      ),
    );
  }

  Widget _buildCompactCourseCard(Course course) {
    return GestureDetector(
      onTap: () => _navigateToCourseDetail(course),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: ThemeColors.primary.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Icon(
                    Icons.play_circle_outline,
                    color: ThemeColors.primary,
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        course.title,
                        style: const TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      Text(
                        course.instructor.name,
                        style: TextStyle(
                          fontSize: 12,
                          color: ThemeColors.textSecondary,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Row(
              children: [
                Icon(
                  Icons.people,
                  size: 14,
                  color: ThemeColors.textSecondary,
                ),
                const SizedBox(width: 4),
                Text(
                  '${course.enrolledCount}人',
                  style: TextStyle(
                    fontSize: 11,
                    color: ThemeColors.textSecondary,
                  ),
                ),
                const Spacer(),
                Text(
                  course.price > 0 ? '¥${course.price}' : '免费',
                  style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.bold,
                    color: course.price > 0 ? ThemeColors.primary : Colors.green,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCourseCategories() {
    final categories = [
      {'name': '传统工艺', 'icon': Icons.handyman, 'color': Colors.blue},
      {'name': '文化理论', 'icon': Icons.menu_book, 'color': Colors.green},
      {'name': '艺术创作', 'icon': Icons.palette, 'color': Colors.orange},
      {'name': '技能培训', 'icon': Icons.build, 'color': Colors.purple},
    ];

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 2.5,
          crossAxisSpacing: 12,
          mainAxisSpacing: 12,
        ),
        itemCount: categories.length,
        itemBuilder: (context, index) {
          final category = categories[index];
          return GestureDetector(
            onTap: () {
              // 根据分类筛选课程
            },
            child: Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 8,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Row(
                children: [
                  Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: (category['color'] as Color).withOpacity(0.1),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Icon(
                      category['icon'] as IconData,
                      color: category['color'] as Color,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          category['name'] as String,
                          style: const TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        Text(
                          '12门课程',
                          style: TextStyle(
                            fontSize: 11,
                            color: ThemeColors.textSecondary,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildPathCard(
    String title,
    String description,
    List<String> steps,
    Color color,
    IconData icon,
  ) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 50,
                height: 50,
                decoration: BoxDecoration(
                  color: color.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Icon(
                  icon,
                  color: color,
                  size: 24,
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      description,
                      style: TextStyle(
                        fontSize: 14,
                        color: ThemeColors.textSecondary,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 20),
          Row(
            children: steps.asMap().entries.map((entry) {
              final index = entry.key;
              final step = entry.value;
              return Expanded(
                child: Row(
                  children: [
                    Expanded(
                      child: Column(
                        children: [
                          Container(
                            width: 30,
                            height: 30,
                            decoration: BoxDecoration(
                              color: color,
                              shape: BoxShape.circle,
                            ),
                            child: Center(
                              child: Text(
                                '${index + 1}',
                                style: const TextStyle(
                                  color: Colors.white,
                                  fontSize: 12,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                          const SizedBox(height: 8),
                          Text(
                            step,
                            style: const TextStyle(
                              fontSize: 11,
                              fontWeight: FontWeight.w500,
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ],
                      ),
                    ),
                    if (index < steps.length - 1)
                      Container(
                        width: 20,
                        height: 2,
                        color: color.withOpacity(0.3),
                        margin: const EdgeInsets.only(bottom: 30),
                      ),
                  ],
                ),
              );
            }).toList(),
          ),
          const SizedBox(height: 20),
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: () {
                // 开始学习路径
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: color,
                padding: const EdgeInsets.symmetric(vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: const Text(
                '开始学习',
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildInstructorCard(Instructor instructor) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          Row(
            children: [
              CircleAvatar(
                radius: 30,
                backgroundColor: ThemeColors.primary.withOpacity(0.1),
                child: Text(
                  instructor.name.substring(0, 1),
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: ThemeColors.primary,
                  ),
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      instructor.name,
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      instructor.title,
                      style: TextStyle(
                        fontSize: 14,
                        color: ThemeColors.primary,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Row(
                      children: [
                        Icon(
                          Icons.star,
                          size: 16,
                          color: Colors.amber,
                        ),
                        const SizedBox(width: 4),
                        Text(
                          instructor.rating.toString(),
                          style: const TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                        const SizedBox(width: 12),
                        Icon(
                          Icons.people,
                          size: 16,
                          color: ThemeColors.textSecondary,
                        ),
                        const SizedBox(width: 4),
                        Text(
                          '${instructor.studentCount}学员',
                          style: TextStyle(
                            fontSize: 12,
                            color: ThemeColors.textSecondary,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Text(
            instructor.bio,
            style: TextStyle(
              fontSize: 14,
              color: ThemeColors.textSecondary,
              height: 1.5,
            ),
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: OutlinedButton(
                  onPressed: () {
                    // 查看讲师详情
                  },
                  style: OutlinedButton.styleFrom(
                    side: BorderSide(color: ThemeColors.primary),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: Text(
                    '查看详情',
                    style: TextStyle(color: ThemeColors.primary),
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: ElevatedButton(
                  onPressed: () {
                    // 关注讲师
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: ThemeColors.primary,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: const Text(
                    '关注',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildCommunitySection(
    String title,
    String description,
    IconData icon,
    Color color,
  ) {
    return GestureDetector(
      onTap: () {
        // 进入对应社区功能
      },
      child: Container(
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 10,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Row(
          children: [
            Container(
              width: 50,
              height: 50,
              decoration: BoxDecoration(
                color: color.withOpacity(0.1),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(
                icon,
                color: color,
                size: 24,
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    description,
                    style: TextStyle(
                      fontSize: 14,
                      color: ThemeColors.textSecondary,
                    ),
                  ),
                ],
              ),
            ),
            Icon(
              Icons.arrow_forward_ios,
              size: 16,
              color: ThemeColors.textSecondary,
            ),
          ],
        ),
      ),
    );
  }

  void _showFilterSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => CourseFilterSheet(
        selectedType: null,
        selectedDifficulty: null,
        selectedStatus: null,
        isFree: null,
        onFilterChanged: ({type, difficulty, status, isFree}) {
          // 处理筛选变化
          _applyFilter(CourseFilter.all); // 临时处理
        },
      ),
    );
  }

  void _navigateToCourseDetail(Course course) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => CourseDetailScreen(courseId: course.id),
      ),
    );
  }
}